package com.jacen.fzxs.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jacen.fzxs.dao.IBaseDao;
import com.jacen.fzxs.dao.IRightDao;
import com.jacen.fzxs.dao.IRoleRightDao;
import com.jacen.fzxs.dao.IRoleUserDao;
import com.jacen.fzxs.entity.RightEntity;
import com.jacen.fzxs.entity.RoleRightEntity;
import com.jacen.fzxs.entity.RoleUserEntity;
import com.jacen.fzxs.entity.UserEntity;
import com.jacen.fzxs.service.IRoleRightService;
import com.jacen.fzxs.util.EntityUtils;

/**
 * 
 * @author Jacen
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleRightService extends BaseService<RoleRightEntity> implements IRoleRightService {
	
	@Resource
	private IRoleRightDao roleRightDao;
	@Resource
	private IRightDao rightDao;
	@Resource
	private IRoleUserDao roleUserDao;

	
	@Override
	public IBaseDao<RoleRightEntity> getDao() {
		return roleRightDao;
	}

	@Override
	public void getUserRight(HttpSession session,UserEntity user) throws Exception {
		RoleUserEntity roleUser = roleUserDao.getByKey("user_id", user.getId());
		if(roleUser==null){
			throw new Exception("用户未分配角色");
		}
		List<RightEntity> list = rightDao.getListByRole(roleUser.getRoleId());
		Set<String> rightSets = new HashSet<String>();
		for(RightEntity entity : list){
			rightSets.add(entity.getRightMark());
		}
		session.setAttribute("rightMarkSession", rightSets);
	}

	@Override
	public void updateRightByRole(String roleId, String selectStr) throws Exception {
		// TODO Auto-generated method stub
		roleRightDao.deleteByKey("role_Id", roleId);
		String[] ids = selectStr.split(",");
		RoleRightEntity entity = null;
		List<RoleRightEntity> list = new ArrayList<RoleRightEntity>();
		for(String id : ids){
			entity = new RoleRightEntity();
			entity.setId(EntityUtils.createId32());
			entity.setRoleId(roleId);
			entity.setRightId(id);
			list.add(entity);
		}
		roleRightDao.insert(list);
	}

}
